<?php
App::uses('CakeNumber', 'Utility');

class ProductsController extends AppController {
	var $uses = array('Producttype','Product');
	var $components = array('Cart','RequestHandler');
	var $helpers = array('ProductBuilder');
	
	public function beforeRender(){
		$this->set('isrental',true);
	}
	
	///View all the products or parse them by category
	public function index($productTypeId = 0){
		$this->set('subtitle','Louez notre vaisselle r&eacute;utilisable');
		$this->set('paragraph_for_subtitle','D&eacute;couvrez nos gammes de produits.');
		$productList = array();
		if($productTypeId == 0){
			$productTypes = $this->Producttype->find('all');
		}else{
			$productTypes = array(array(
				'Producttype' => array(
					'id' => $productTypeId)
				));
		}
		foreach($productTypes as $productType){
			$productTypeArray = $productType['Producttype'];
			$currentProductList = $this->Product->query('call product_getproductbyproducttypeid('.$productTypeArray['id'].');');
			$currentproductType = $this->Producttype->findByid($productTypeArray['id']);
			$productList[$currentproductType['Producttype']['name']] = $currentProductList;
		}
		$this->set('ProductList', $productList);		
	}
	
	/**
	**View One Particular Product in details
	**/
	public function view($id=0){
		$product = $this->Product->query('call product_getproductbyid('.$id.');');
		$this->set('subtitle',$product[0]['products']['name'].' | '.$product[0]['producttypes']['name']);
		$this->set('paragraph_for_subtitle','D&eacute;couvrez notre produit.');
		$this->set('Product',$product);
	}
	
	public function search(){
	
	}
	
	/**Add a product to the cart
	@Input:
	Product
		- productId
		- number
		
	@output:
	Cart:
		items
		price
		associateprice
		bond
	**/
	public function add()
	{
		Configure::write('debug',0);
		$this->layout = 'ajax';
		if(!empty($this->data)){
			$request = json_decode($this->data,true);
			$productid = $request['id'];
			$number = $request['number'];
			$response = $this->Cart->addOrder($productid, $number);

			echo json_encode($response);
			exit;
		}
		echo json_encode(false);
		exit;
	}
}
?>